using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Read.API.Applications.Commands.customers;
using SupplierCustomerManagement.Read.API.Dtos;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.customers
{
    /// <summary>
    /// 根据ID获取客户详细信息查询处理器
    /// </summary>
    public class GetCustomerByIdQueryHandler : IRequestHandler<GetCustomerByIdQuery, ApiResult<CustomerDetailDto>>
    {
        private readonly IBaseRepository<Customer> _customerRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetCustomerByIdQueryHandler> _logger;

        public GetCustomerByIdQueryHandler(
            IBaseRepository<Customer> customerRepository,
            IMapper mapper,
            ILogger<GetCustomerByIdQueryHandler> logger)
        {
            _customerRepository = customerRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理根据ID获取客户详细信息查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>客户详细信息</returns>
        public async Task<ApiResult<CustomerDetailDto>> Handle(GetCustomerByIdQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询客户详细信息，客户ID: {CustomerId}", request.Id);

                // 根据ID查询客户信息
                var customer = await _customerRepository.GetAll()
                    .Where(c => c.Id == request.Id && !c.IsDeleted)
                    .FirstOrDefaultAsync(cancellationToken);

                // 检查客户是否存在
                if (customer == null)
                {
                    _logger.LogWarning("未找到指定的客户，客户ID: {CustomerId}", request.Id);
                    
                    return new ApiResult<CustomerDetailDto>
                    {
                        code = ResultEnumCode.fails,
                        message = "未找到指定的客户",
                        data = default
                    };
                }

                // 映射到DTO
                var customerDetailDto = _mapper.Map<CustomerDetailDto>(customer);

                _logger.LogInformation("成功查询客户详细信息，客户ID: {CustomerId}, 客户名称: {CustomerName}", 
                    request.Id, customer.Name);

                return new ApiResult<CustomerDetailDto>
                {
                    code = ResultEnumCode.Ok,
                    message = "查询成功",
                    data = customerDetailDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询客户详细信息时发生异常，客户ID: {CustomerId}", request.Id);
                
                return new ApiResult<CustomerDetailDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"查询客户详细信息时发生异常: {ex.Message}",
                    data = default
                };
            }
        }
    }
}
